package com.lmz.product.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.lmz.common.valid.addGroup;
import com.lmz.common.valid.updateGroup;
import com.lmz.common.valid.updateStatusGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.lmz.product.entity.BrandEntity;
import com.lmz.product.service.BrandService;
import com.lmz.common.utils.PageUtils;
import com.lmz.common.utils.R;

import javax.validation.Valid;


/**
 * 品牌
 *
 * @author lmz
 * @date 2022-04-17 16:10:00
 */
@RestController
@RequestMapping("product/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;

    /**
     * 返回所有品牌数据
     */

    @GetMapping("/infos")
    public R info(@RequestParam("brandIds") List<Long> brandIds) {
        List<BrandEntity> brands = brandService.getBrandsByIds(brandIds);
        return R.ok().put("brand", brands);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = brandService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{brandId}")
    public R info(@PathVariable("brandId") Long brandId) {
        BrandEntity brand = brandService.getById(brandId);

        return R.ok().put("brand", brand);
    }

    /**
     * 保存-新增
     *
     * @Valid: 告诉springMVC数据需要进行校验
     * BindingResult:封装了校验结果,此处抛出去交给统一异常处理
     */
    @RequestMapping("/save")
    public R save(@Validated(value = {addGroup.class}) @RequestBody BrandEntity brand /*,BindingResult result*/) {
        brandService.save(brand);
        return R.ok();
        //if (result.hasErrors()) {
        //    Map<String, String> map = new HashMap<>();
        //    result.getFieldErrors().forEach((item) -> {
        //        String err = item.getDefaultMessage();
        //        String field = item.getField();
        //        map.put(field, err);
        //    });
        //    return R.error(400, "提交的数据不合法").put("data", map);
        //} else {
        //}
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@Validated(value = updateGroup.class) @RequestBody BrandEntity brand) {
        brandService.updateByIdDetail(brand);
        return R.ok();
    }

    /**
     * 修改状态
     */
    @RequestMapping("/update/status")
    public R updateStatus(@Validated(value = updateStatusGroup.class) @RequestBody BrandEntity brand) {
        brandService.updateById(brand);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] brandIds) {
        brandService.removeByIds(Arrays.asList(brandIds));

        return R.ok();
    }

}